const app = getApp()
const { formatDate } = require('../../lib/util')
const { getCateData, getMonthData } = require('../../api/bill')
const wxCharts = require('../../lib/wxcharts')

Page({
  /** 页面的初始数据 */
  data: {
    currentIndex: 0,
    switches: [
      { name: '花 费' },
      { name: '收 入' }
    ],
    begin: formatDate('yyyy-MM') + '-01',
    end: formatDate('yyyy-MM-dd'),
    type: 'pie',
    stat: false,
    isEmpty: true
  },
  /** 生命周期函数--监听页面加载 */
  onLoad: function (options) {
    // 记录当前月
    this.begin = formatDate('yyyy-MM') + '-01'
    this.end = formatDate('yyyy-MM-dd')
    // 获取窗口大小
    wx.getSystemInfo({
      success: res => {
        this.windowWidth = res.windowWidth
      }
    })
  },
  onShow() {
    switch (this.data.type) {
      case 'pie':
        this.paintPie()
        return
      case 'column':
        this.paintColumn()
        return
      case 'line':
        this.paintLine()
        return
    }
  },
  paintPie() {
    var currentIndex = this.data.currentIndex
    this.getCateData(res => {
      this.setData({
        'stat.pie': res,
        'isEmpty': res[currentIndex]['series'].length === 0
      })
      if (res[currentIndex]['total'] <= 0) {
        return
      }
      new wxCharts({
        animation: true, //是否有动画
        canvasId: `canvas-pie-${this.data.currentIndex}`,
        type: 'pie',
        legend: true,
        series: res[currentIndex]['series'],
        extra: {
          textColor: '#ffffff',
          legendTextColor: '#ffffff'
        },
        width: this.windowWidth,
        height: 250,
        dataLabel: true
      })
    })
  },
  paintColumn() {
    this.getMonthData(res => {
      this.setData({
        'isEmpty': Object.keys(res['categories']).length === 0
      })
      if (Object.keys(res.categories).length <= 0) {
        return
      }
      console.log(res)
      this.chart = new wxCharts({
        animation: true,
        canvasId: 'canvas-column',
        type: 'column',
        categories: Object.keys(res.categories),
        series: [{
          name: '花费',
          data: Object.values(res.series[0]),
          color: '#f06292',
          textColor: '#ffffff'
        }, {
          name: '收入',
          data: Object.values(res.series[1]),
          color: '#81c784',
          textColor: '#ffffff'
        }],
        yAxis: {
          fontColor: '#ffffff',
          min: 0
        },
        xAxis: {
          disableGrid: true,
          fontColor: '#ffffff'
        },
        extra: {
          legendTextColor: '#ffffff',
          column: {
            width: 15
          }
        },
        width: this.windowWidth,
        height: 250,
        dataLabel: true
      })
    })
  },
  paintLine() {
    this.getMonthData(res => {
      this.setData({
        'isEmpty': Object.keys(res['categories']).length === 0
      })
      if (Object.keys(res.categories).length <= 0) {
        return
      }
      // 计算余额
      // var remain = res.categories
      // for (let key in res.categories) {
      //   remain[key] = +(res.series[1][key] - res.series[0][key]).toFixed(2)
      // }
      new wxCharts({
        canvasId: 'canvas-line',
        type: 'line',
        categories: Object.keys(res.categories),
        series: [{
          name: '花费',
          data: Object.values(res.series[0]),
          textColor: '#ffffff'
        }, {
          name: '收入',
          data: Object.values(res.series[1]),
          textColor: '#ffffff'
        },
        // {
        //   name: '余额',
        //   data: Object.values(remain),
        //   textColor: '#ffffff'
        // }
        ],
        yAxis: {
          // title: '金额 (元)',
          fontColor: '#ffffff',
          titleFontColor: '#ffffff',
          min: 0
        },
        xAxis: {
          disableGrid: true,
          fontColor: '#ffffff'
        },
        extra: {
          legendTextColor: '#ffffff',
          radar: {
            labelColor: '#ffffff'
          }
        },
        width: this.windowWidth,
        height: 250,
        dataLabel: true
      })
    })
  },
  onDateChange (e) {
    var type = e.detail.type
    var value = e.detail.value
    if (type === 'begin' && value > this.data.end 
      || type === 'end' && this.data.begin > value) {
        wx.showToast({
          icon: 'none',
          title: '开始时间不能大于结束时间',
        })
        return
    }
    this.setData({
      [type]: value,
      stat: false
    })
    switch (this.data.type) {
      case 'pie':
        this.paintPie()
        return
      case 'column':
        this.paintColumn()
        return
      case 'line':
        this.paintLine()
        return
    }
  },
  toggleType(e) {
    var type = e.currentTarget.dataset.type
    this.setData({
      type: type
    })
    if (type === 'pie') {
      this.paintPie()
    } else {
      this.paintColumn()
    }
  },
  onSwitch(e) {
    this.setData({
      currentIndex: e.detail.index
    })
    this.paintPie()
  },
  showLine() {
    this.paintLine()
    this.setData({
      type: 'line'
    })
  },
  backColumn() {
    this.paintColumn()
    this.setData({
      type: 'column'
    })
  },
  getCateData(cb) {
    var cache = wx.getStorageSync('stat_pie')
    if (cache && this.data.begin === cache.begin && this.data.end === cache.end) {
      console.log('本地：Cate')
      typeof cb === 'function' && cb(cache.data)
      return
    }
    // 查询
    console.log('数据库：Cate')
    getCateData({
      begin: this.data.begin,
      end: this.data.end
    }).then(res => {
      var list = res.list
      console.log(list)
      var data = [
        { total: 0, series: [] },
        { total: 0, series: [] }
      ]
      list.forEach(item => {
        data[item._id.type]['total'] += +item.money.toFixed(2)
        data[item._id.type]['series'].push({
          name: item._id.category,
          data: +item.money.toFixed(2)
        })
      })
      data[0]['total'] = +parseFloat(data[0]['total']).toFixed(2)
      data[1]['total'] = +parseFloat(data[1]['total']).toFixed(2)
      this.setData({
        'stat.pie': data
      })
      if (this.begin === this.data.begin && this.end === this.data.end) {
        wx.setStorageSync('stat_pie', {
          begin: this.begin,
          end: this.end,
          data: data
        })
      }
      typeof cb === 'function' && cb(data)
    })
  },
  getMonthData(cb) {
    var cache = wx.getStorageSync('stat_com')
    if (cache && this.data.begin === cache.begin && this.data.end === cache.end && cache.data) {
      console.log('本地：Month')
      typeof cb === 'function' && cb(cache.data)
      return
    }
    console.log('数据库：Month')
    getMonthData({
      begin: this.data.begin,
      end: this.data.end
    }).then(res => {
      var list = res.list
      var data = {
        categories: {},
        series: [{}, {}]
      }
      var monthBegin = new Date(this.data.begin)
      var monthEnd = new Date(this.data.end)
      while (monthBegin <= monthEnd) {
        var key = formatDate('yyyy-MM', monthBegin)
        data.categories[key] = 1
        data.series[0][key] = 0
        data.series[1][key] = 0
        monthBegin.setMonth(monthBegin.getMonth() + 1)
      }
      list.forEach(item => {
        data.categories[item._id.month] = 1
        if (item._id.type === 0) {
          data['series'][0][item._id.month] = +item.money.toFixed(2)
          data['series'][1][item._id.month] = data['series'][1][item._id.month] ? data['series'][1][item._id.month] : 0
        } else {
          data['series'][1][item._id.month] = +item.money.toFixed(2)
          data['series'][0][item._id.month] = data['series'][0][item._id.month] ? data['series'][0][item._id.month] : 0
        }
      })
      // console.log(data)
      this.setData({
        'stat.com': data
      })
      if (this.begin === this.data.begin && this.end === this.data.end) {
        wx.setStorageSync('stat_com', {
          begin: this.begin,
          end: this.end,
          data: data
        })
      }
      typeof cb === 'function' && cb(data)
    })
  }
})